package com.lefevre.cms.web.action.help;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lefevre.cms.bean.*;
import com.lefevre.cms.bean.help.Help;
import com.lefevre.cms.bean.help.HelpType;
import com.lefevre.cms.bean.mediaProcess.MediaProcessQueue;
import com.lefevre.cms.bean.setting.SystemSetting;
import com.lefevre.cms.service.help.HelpService;
import com.lefevre.cms.service.help.HelpTypeService;
import com.lefevre.cms.service.mediaProcess.MediaProcessService;
import com.lefevre.cms.service.setting.SettingService;
import com.lefevre.cms.utils.CommentedProperties;
import com.lefevre.cms.utils.FileUtil;
import com.lefevre.cms.utils.JsonUtils;
import com.lefevre.cms.utils.UUIDUtil;
import com.lefevre.cms.web.action.TextFilterManage;
import com.lefevre.cms.web.action.fileSystem.FileManage;
import com.lefevre.cms.web.action.mediaProcess.MediaProcessQueueManage;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

/**
 * 帮助管理
 *
 * @author Lefevre
 */
@Controller
@RequestMapping("/control/help/manage")
public class AdminHelpController {
    private static final Logger logger = LoggerFactory.getLogger(AdminHelpController.class);

    @Resource
    HelpService helpService;
    @Resource
    HelpTypeService helpTypeService;
    @Resource
    TextFilterManage textFilterManage;
    @Resource
    SettingService settingService;
    @Resource
    FileManage fileManage;
    @Resource
    MediaProcessService mediaProcessService;
    @Resource
    MediaProcessQueueManage mediaProcessQueueManage;

    /**
     * 帮助   查看
     */
    @ResponseBody
    @RequestMapping(params = "method=view", method = RequestMethod.GET)
    public String view(Long helpId) throws Exception {
        Map<String, String> error = new HashMap<>();
        if (helpId != null && helpId > 0L) {
            Help help = helpService.findById(helpId);
            if (help != null) {
                HelpType helpType = helpTypeService.findById(help.getHelpTypeId());
                if (helpType != null) {
                    help.setHelpTypeName(helpType.getName());
                }
                SystemSetting systemSetting = settingService.findSystemSetting_cache();
                //处理富文本路径
                help.setContent(fileManage.processRichTextFilePath(help.getContent(), "help"));
                if (help.getContent() != null && !"".equals(help.getContent().trim())) {
                    //处理视频播放器标签
                    String content = textFilterManage.processVideoPlayer(help.getContent(), -1L,
                            systemSetting.getFileSecureLinkSecret());
                    help.setContent(content);
                }
                return JsonUtils.toJSONString(new RequestResult(ResultCode.SUCCESS, help));
            } else {
                error.put("helpId", "帮助不存在");
            }
        } else {
            error.put("helpId", "帮助Id不存在");
        }
        return JsonUtils.toJSONString(new RequestResult(ResultCode.FAILURE, error));
    }

    /**
     * 帮助   添加界面显示
     */
    @ResponseBody
    @RequestMapping(params = "method=add", method = RequestMethod.GET)
    public String addUI() throws Exception {
        return JsonUtils.toJSONString(new RequestResult(ResultCode.SUCCESS, null));
    }

    /**
     * 帮助  添加
     */
    @ResponseBody
    @RequestMapping(params = "method=add", method = RequestMethod.POST)
    public String add(ModelMap model, Long helpTypeId, String helpTypeName, String name, String content, HttpServletRequest request) throws Exception {
        Map<String, String> error = new HashMap<>();

        Help help = new Help();
        List<String> imageNameList = null;
        boolean isImage;//是否含有图片
        List<String> flashNameList = null;
        boolean isFlash;//是否含有Flash
        List<String> mediaNameList = null;
        boolean isMedia = false;//是否含有音视频
        List<String> fileNameList = null;
        boolean isFile;//是否含有文件
        boolean isMap;//是否含有地图

        //复制文件锁
        List<String> fileLock_list = new ArrayList<>();
        List<String> oldPathFileList = new ArrayList<>();//旧路径文件

        help.setHelpTypeId(helpTypeId);
        help.setHelpTypeName(helpTypeName);

        if (helpTypeId == null || helpTypeId <= 0L) {
            error.put("helpTypeId", "帮助分类不能为空");
        } else {

            if (name != null && !"".equals(name.trim())) {
                help.setName(name);
                if (name.length() > 50) {
                    error.put("name", "不能大于100个字符");
                }
            } else {
                error.put("name", "帮助名称不能为空");
            }
            if (content != null && !"".equals(content.trim())) {
                //过滤标签
                content = textFilterManage.filterTag(request, content);
                Object[] object = textFilterManage.filterHtml(request, content, "help", null);
                String value = (String) object[0];
                imageNameList = (List<String>) object[1];
                isImage = (Boolean) object[2];//是否含有图片
                flashNameList = (List<String>) object[3];
                isFlash = (Boolean) object[4];//是否含有Flash
                mediaNameList = (List<String>) object[5];
                isMedia = (Boolean) object[6];//是否含有音视频
                fileNameList = (List<String>) object[7];
                isFile = (Boolean) object[8];//是否含有文件
                isMap = (Boolean) object[9];//是否含有地图

                //修改文件路径
                Object[] path_object = textFilterManage.updateTypePath(value, "help", helpTypeId);
                String new_value = (String) path_object[0];
                Map<String, String> file_path = (Map<String, String>) path_object[1];//key:旧文件路径  value:新文件路径

                if (file_path != null && file_path.size() > 0) {
                    for (Map.Entry<String, String> entry : file_path.entrySet()) {//key:旧文件路径  value:新文件路径

                        //旧路径 左斜杆路径转为系统路径
                        String old_path_Delimiter = FileUtil.toSystemPath(entry.getKey());

                        //新路径 左斜杆路径转为系统路径
                        String new_path_Delimiter = FileUtil.toSystemPath(entry.getValue());

                        //替换路径中的..号
                        old_path_Delimiter = FileUtil.toRelativePath(old_path_Delimiter);
                        new_path_Delimiter = FileUtil.toRelativePath(new_path_Delimiter);

                        //复制文件到新路径
                        fileManage.copyFile(old_path_Delimiter, new_path_Delimiter);
                        //取得文件名称
                        String fileName = FileUtil.getName(entry.getKey());

                        //新建文件锁到新路径
                        //生成锁文件名称
                        String lockFileName = StringUtils.replaceOnce(entry.getValue(), "file/help/", "")
                                + fileName;
                        lockFileName = lockFileName.replaceAll("/", "_");

                        fileLock_list.add(lockFileName);
                        //添加文件锁
                        fileManage.addLock("file" + File.separator + "help" + File.separator + "lock"
                                + File.separator, lockFileName);
                        //旧路径文件
                        oldPathFileList.add(old_path_Delimiter);
                    }
                }
                //不含标签内容
                String text = textFilterManage.filterText(content);
                //清除空格&nbsp;
                String trimSpace = com.lefevre.cms.utils.StringUtil.replaceSpace(text).trim();
                if (isImage || isFlash || isMedia || isFile || isMap || (!"".equals(text.trim()) && !"".equals(trimSpace))) {
                    String username = "";
                    Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                    if (obj instanceof UserDetails) {
                        username = ((UserDetails) obj).getUsername();
                    }
                    help.setUserName(username);
                    help.setContent(new_value);
                } else {
                    error.put("content", "帮助内容不能为空");
                }
            } else {
                error.put("content", "帮助内容不能为空");
            }
        }
        if (error.size() == 0) {
            int i = helpService.saveHelp(help);

            if (i == 0) {
                error.put("content", "帮助添加失败");
                model.addAttribute("error", error);
            } else {
                if (isMedia) {
                    Object[] object = textFilterManage.readPathName(help.getContent(), "help");
                    List<String> newMediaNameList = (List<String>) object[2];

                    List<MediaProcessQueue> mediaProcessQueueList = new ArrayList<MediaProcessQueue>();
                    for (String fullPathName : newMediaNameList) {
                        //取得路径名称
                        String pathName = FileUtil.getFullPath(fullPathName);
                        //文件名称
                        String fileName = FileUtil.getName(fullPathName);

                        MediaProcessQueue mediaProcessQueue = new MediaProcessQueue();
                        mediaProcessQueue.setModule(60);//60:在线帮助
                        mediaProcessQueue.setType(10);//10:视频
                        mediaProcessQueue.setParameter(String.valueOf(help.getId()));
                        mediaProcessQueue.setPostTime(help.getTimes());
                        mediaProcessQueue.setFilePath(pathName);
                        mediaProcessQueue.setFileName(fileName);
                        mediaProcessQueueList.add(mediaProcessQueue);
                    }
                    mediaProcessService.saveMediaProcessQueueList(mediaProcessQueueList);
                }

                //删除图片锁
                if (imageNameList != null && imageNameList.size() > 0) {
                    for (String imageName : imageNameList) {

                        if (imageName != null && !"".equals(imageName.trim())) {
                            fileManage.deleteLock("file" + File.separator + "help" + File.separator + "lock"
                                    + File.separator, imageName.replaceAll("/", "_"));
                        }
                    }
                }
                //falsh
                if (flashNameList != null && flashNameList.size() > 0) {
                    for (String flashName : flashNameList) {

                        if (flashName != null && !"".equals(flashName.trim())) {
                            fileManage.deleteLock("file" + File.separator + "help" + File.separator + "lock"
                                    + File.separator, flashName.replaceAll("/", "_"));
                        }
                    }
                }
                //音视频
                if (mediaNameList != null && mediaNameList.size() > 0) {
                    for (String mediaName : mediaNameList) {
                        if (mediaName != null && !"".equals(mediaName.trim())) {
                            fileManage.deleteLock("file" + File.separator + "help" + File.separator + "lock"
                                    + File.separator, mediaName.replaceAll("/", "_"));
                        }
                    }
                }
                //文件
                if (fileNameList != null && fileNameList.size() > 0) {
                    for (String fileName : fileNameList) {
                        if (fileName != null && !"".equals(fileName.trim())) {
                            fileManage.deleteLock("file" + File.separator + "help" + File.separator + "lock"
                                    + File.separator, fileName.replaceAll("/", "_"));
                        }
                    }
                }
                //删除复制文件锁
                if (fileLock_list.size() > 0) {
                    for (String fileName : fileLock_list) {
                        if (fileName != null && !"".equals(fileName.trim())) {
                            fileManage.deleteLock("file" + File.separator + "help" + File.separator + "lock"
                                    + File.separator, fileName.replaceAll("/", "_"));
                        }
                    }
                }

                //删除旧路径文件
                if (oldPathFileList.size() > 0) {
                    for (String oldPathFile : oldPathFileList) {
                        //替换路径中的..号
                        oldPathFile = FileUtil.toRelativePath(oldPathFile);
                        Boolean state = fileManage.deleteFile(oldPathFile);
                        if (state != null && !state) {
                            //替换指定的字符，只替换第一次出现的
                            oldPathFile = StringUtils.replaceOnce(oldPathFile, "file" + File.separator + "help"
                                    + File.separator, "");

                            //创建删除失败文件
                            fileManage.failedStateFile("file" + File.separator + "help" + File.separator + "lock"
                                    + File.separator + FileUtil.toUnderline(oldPathFile));
                        }
                    }
                }
            }
        }

        if (error.size() > 0) {
            return JsonUtils.toJSONString(new RequestResult(ResultCode.FAILURE, error));
        } else {
            return JsonUtils.toJSONString(new RequestResult(ResultCode.SUCCESS, null));
        }
    }

    /**
     * 文件上传
     *
     * @param dir:     上传类型，分别为image、flash、media、file
     * @param fileName 文件名称 预签名时有值
     */
    @ResponseBody
    @RequestMapping(params = "method=upload", method = RequestMethod.POST)
    public String upload(Long helpTypeId, String dir, String fileName, MultipartFile file) throws Exception {
        Map<String, Object> returnJson = new HashMap<>();
        String errorMessage = "";
        if (dir != null) {
            DateTime dateTime = new DateTime();

            String date = dateTime.toString("yyyy-MM-dd");
            int fileSystem = fileManage.getFileSystem();
            if (fileSystem == 10 || fileSystem == 20 || fileSystem == 30) {//10.SeaweedFS 20.MinIO 30.阿里云OSS
                if (fileName != null && !"".equals(fileName.trim())) {
                    //取得文件后缀
                    String suffix = FileUtil.getExtension(fileName.trim()).toLowerCase();
                    switch (dir) {
                        case "image": {
                            //允许上传格式
                            List<String> formatList = CommentedProperties.readRichTextAllowImageUploadFormat();
                            //验证文件后缀
                            boolean authentication = FileUtil.validateFileSuffix(fileName.trim(), formatList);
                            if (authentication) {
                                //文件锁目录
                                String lockPathDir = "file" + File.separator + "help" + File.separator + "lock" + File.separator;
                                //构建文件名称
                                String newFileName = UUIDUtil.getUUID32() + "." + suffix;
                                //生成锁文件
                                fileManage.addLock(lockPathDir, helpTypeId + "_" + date + "_image_" + newFileName);
                                String presigne = fileManage.createPresigned("file/help/" + helpTypeId + "/"
                                        + date + "/image/" + newFileName, null);//创建预签名

                                //返回预签名URL
                                returnJson.put("error", 0);//0成功  1错误
                                returnJson.put("url", presigne);
                                returnJson.put("title", fileName);//旧文件名称
                                return JsonUtils.toJSONString(returnJson);
                            } else {
                                errorMessage = "文件格式不允许上传";
                            }
                            break;
                        }
                        case "flash": {
                            //允许上传格式
                            List<String> formatList = new ArrayList<>();
                            formatList.add("swf");
                            //验证文件后缀
                            boolean authentication = FileUtil.validateFileSuffix(fileName.trim(), formatList);
                            if (authentication) {
                                //文件锁目录
                                String lockPathDir = "file" + File.separator + "help" + File.separator + "lock" + File.separator;

                                //构建文件名称
                                String newFileName = UUIDUtil.getUUID32() + "." + suffix;

                                //生成锁文件
                                fileManage.addLock(lockPathDir, helpTypeId + "_" + date + "_flash_" + newFileName);
                                String presigne = fileManage.createPresigned("file/help/" + helpTypeId + "/"
                                        + date + "/flash/" + newFileName, null);//创建预签名

                                //返回预签名URL
                                returnJson.put("error", 0);//0成功  1错误
                                returnJson.put("url", presigne);
                                returnJson.put("title", fileName);//旧文件名称
                                return JsonUtils.toJSONString(returnJson);

                            } else {
                                errorMessage = "文件格式不允许上传";
                            }

                            break;
                        }
                        case "media": {
                            //允许上传格式
                            List<String> formatList = CommentedProperties.readRichTextAllowVideoUploadFormat();
                            //验证文件后缀
                            boolean authentication = FileUtil.validateFileSuffix(fileName.trim(), formatList);
                            if (authentication) {
                                //文件锁目录
                                String lockPathDir = "file" + File.separator + "help" + File.separator + "lock" + File.separator;

                                //构建文件名称
                                String newFileName = UUIDUtil.getUUID32() + "." + suffix;

                                //生成锁文件
                                fileManage.addLock(lockPathDir, helpTypeId + "_" + date + "_media_" + newFileName);
                                String presigne = fileManage.createPresigned("file/help/" + helpTypeId + "/"
                                        + date + "/media/" + newFileName, null);//创建预签名

                                //返回预签名URL
                                returnJson.put("error", 0);//0成功  1错误
                                returnJson.put("url", presigne);
                                returnJson.put("title", fileName);//旧文件名称
                                return JsonUtils.toJSONString(returnJson);

                            } else {
                                errorMessage = "文件格式不允许上传";
                            }
                            break;
                        }
                        case "file": {
                            //允许上传格式
                            List<String> formatList = CommentedProperties.readRichTextAllowFileUploadFormat();

                            //验证文件后缀
                            boolean authentication = FileUtil.validateFileSuffix(fileName.trim(), formatList);
                            if (authentication) {
                                //文件锁目录
                                String lockPathDir = "file" + File.separator + "help" + File.separator + "lock" + File.separator;

                                //构建文件名称
                                String newFileName = UUIDUtil.getUUID32() + "." + suffix;

                                //生成锁文件
                                fileManage.addLock(lockPathDir, helpTypeId + "_" + date + "_file_" + newFileName);
                                String presigne = fileManage.createPresigned("file/help/" + helpTypeId + "/"
                                        + date + "/file/" + newFileName, null);//创建预签名

                                //返回预签名URL
                                returnJson.put("error", 0);//0成功  1错误
                                returnJson.put("url", presigne);
                                returnJson.put("title", fileName);//旧文件名称
                                return JsonUtils.toJSONString(returnJson);
                            } else {
                                errorMessage = "文件格式不允许上传";
                            }
                            break;
                        }
                        default:
                            errorMessage = "缺少dir参数";
                            break;
                    }
                } else {
                    errorMessage = "文件名称不能为空";
                }


            } else {//0.本地系统
                if (file != null && !file.isEmpty()) {
                    //当前文件名称
                    String sourceFileName = file.getOriginalFilename();

                    String suffix = FileUtil.getExtension(sourceFileName).toLowerCase();

                    switch (dir) {
                        case "image": {
                            //允许上传图片格式
                            List<String> formatList = CommentedProperties.readRichTextAllowImageUploadFormat();
                            //验证文件类型
                            boolean authentication = FileUtil.validateFileSuffix(file.getOriginalFilename(), formatList);
                            if (authentication) {
                                //文件保存目录;分多目录主要是为了分散图片目录,提高检索速度
                                String pathDir = "file" + File.separator + "help" + File.separator + helpTypeId
                                        + File.separator + date + File.separator + "image" + File.separator;
                                //文件锁目录
                                String lockPathDir = "file" + File.separator + "help" + File.separator + "lock" + File.separator;

                                //构建文件名称
                                String newFileName = UUIDUtil.getUUID32() + "." + suffix;

                                //生成文件保存目录
                                FileUtil.createFolder(pathDir);
                                //生成锁文件保存目录
                                FileUtil.createFolder(lockPathDir);
                                //生成锁文件
                                fileManage.addLock(lockPathDir, helpTypeId + "_" + date + "_image_" + newFileName);
                                //保存文件
                                fileManage.writeFile(pathDir, newFileName, file.getBytes());


                                //上传成功
                                returnJson.put("error", 0);//0成功  1错误
                                returnJson.put("url", fileManage.fileServerAddress() + "file/help/" + helpTypeId + "/"
                                        + date + "/image/" + newFileName);
                                return JsonUtils.toJSONString(returnJson);

                            } else {
                                errorMessage = "当前文件类型不允许上传";
                            }
                            break;
                        }
                        case "flash": {

                            List<String> flashFormatList = new ArrayList<>();
                            flashFormatList.add("swf");

                            //验证文件后缀
                            boolean authentication = FileUtil.validateFileSuffix(file.getOriginalFilename(), flashFormatList);

                            if (authentication) {

                                String pathDir = "file" + File.separator + "help" + File.separator + helpTypeId
                                        + File.separator + date + File.separator + "flash" + File.separator;
                                //文件锁目录
                                String lockPathDir = "file" + File.separator + "help" + File.separator + "lock" + File.separator;
                                //构建文件名称
                                String newFileName = UUIDUtil.getUUID32() + "." + suffix;

                                //生成文件保存目录
                                FileUtil.createFolder(pathDir);
                                //生成锁文件保存目录
                                FileUtil.createFolder(lockPathDir);
                                //生成锁文件
                                fileManage.addLock(lockPathDir, helpTypeId + "_" + date + "_flash_" + newFileName);
                                //保存文件
                                fileManage.writeFile(pathDir, newFileName, file.getBytes());


                                //上传成功
                                returnJson.put("error", 0);//0成功  1错误
                                returnJson.put("url", fileManage.fileServerAddress() + "file/help/" + helpTypeId + "/"
                                        + date + "/flash/" + newFileName);
                                return JsonUtils.toJSONString(returnJson);
                            } else {
                                errorMessage = "当前文件类型不允许上传";
                            }


                            break;
                        }
                        case "media": {
                            //允许上传视音频格式
                            List<String> formatList = CommentedProperties.readRichTextAllowVideoUploadFormat();


                            //验证文件后缀
                            boolean authentication = FileUtil.validateFileSuffix(file.getOriginalFilename(), formatList);

                            if (authentication) {
                                //文件保存目录;分多目录主要是为了分散图片目录,提高检索速度
                                String pathDir = "file" + File.separator + "help" + File.separator + helpTypeId
                                        + File.separator + date + File.separator + "media" + File.separator;
                                //文件锁目录
                                String lockPathDir = "file" + File.separator + "help" + File.separator + "lock" + File.separator;
                                //构建文件名称
                                String newFileName = UUIDUtil.getUUID32() + "." + suffix;
                                //生成文件保存目录
                                FileUtil.createFolder(pathDir);
                                //生成锁文件保存目录
                                FileUtil.createFolder(lockPathDir);
                                //生成锁文件
                                fileManage.addLock(lockPathDir, helpTypeId + "_" + date + "_media_" + newFileName);
                                //保存文件
                                fileManage.writeFile(pathDir, newFileName, file.getBytes());

                                //上传成功
                                returnJson.put("error", 0);//0成功  1错误
                                returnJson.put("url", fileManage.fileServerAddress() + "file/help/" + helpTypeId + "/"
                                        + date + "/media/" + newFileName);
                                return JsonUtils.toJSONString(returnJson);
                            } else {
                                errorMessage = "当前文件类型不允许上传";
                            }
                            break;
                        }
                        case "file": {
                            //允许上传文件格式
                            List<String> formatList = CommentedProperties.readRichTextAllowFileUploadFormat();
                            //验证文件后缀
                            boolean authentication = FileUtil.validateFileSuffix(file.getOriginalFilename(), formatList);
                            if (authentication) {
                                //文件保存目录;分多目录主要是为了分散图片目录,提高检索速度
                                String pathDir = "file" + File.separator + "help" + File.separator + helpTypeId
                                        + File.separator + date + File.separator + "file" + File.separator;
                                //文件锁目录
                                String lockPathDir = "file" + File.separator + "help" + File.separator + "lock" + File.separator;
                                //构建文件名称
                                String newFileName = UUIDUtil.getUUID32() + "." + suffix;

                                //生成文件保存目录
                                FileUtil.createFolder(pathDir);
                                //生成锁文件保存目录
                                FileUtil.createFolder(lockPathDir);
                                //生成锁文件
                                fileManage.addLock(lockPathDir, helpTypeId + "_" + date + "_file_" + newFileName);
                                //保存文件
                                fileManage.writeFile(pathDir, newFileName, file.getBytes());

                                //上传成功
                                returnJson.put("error", 0);//0成功  1错误
                                returnJson.put("url", fileManage.fileServerAddress() + "file/help/" + helpTypeId + "/"
                                        + date + "/file/" + newFileName);
                                returnJson.put("title", file.getOriginalFilename());//旧文件名称
                                return JsonUtils.toJSONString(returnJson);
                            } else {
                                errorMessage = "当前文件类型不允许上传";
                            }
                            break;
                        }
                        default:
                            errorMessage = "缺少dir参数";
                            break;
                    }
                } else {
                    errorMessage = "文件不能为空";
                }
            }
        } else {
            errorMessage = "参数不能为空";
        }

        //上传失败
        returnJson.put("error", 1);
        returnJson.put("message", errorMessage);
        return JsonUtils.toJSONString(returnJson);
    }

    /**
     * 帮助   修改界面显示
     */
    @ResponseBody
    @RequestMapping(params = "method=edit", method = RequestMethod.GET)
    public String editUI(Long helpId) throws Exception {
        Map<String, String> error = new HashMap<>();

        if (helpId != null && helpId > 0L) {
            Help help = helpService.findById(helpId);
            if (help != null) {
                HelpType helpType = helpTypeService.findById(help.getHelpTypeId());
                if (helpType != null) {
                    help.setHelpTypeName(helpType.getName());
                }
                //处理富文本路径
                help.setContent(fileManage.processRichTextFilePath(help.getContent(), "help"));
                return JsonUtils.toJSONString(new RequestResult(ResultCode.SUCCESS, help));
            } else {
                error.put("helpId", "帮助不存在");
            }
        } else {
            error.put("helpId", "帮助Id不能为空");
        }

        return JsonUtils.toJSONString(new RequestResult(ResultCode.FAILURE, error));
    }

    /**
     * 帮助   修改
     */
    @ResponseBody
    @RequestMapping(params = "method=edit", method = RequestMethod.POST)
    public String edit(Long helpId, Long helpTypeId, String name, String content, HttpServletRequest request) throws Exception {
        Map<String, String> error = new HashMap<>();

        Help help = null;
        List<String> imageNameList = null;
        boolean isImage = false;//是否含有图片
        List<String> flashNameList = null;
        boolean isFlash = false;//是否含有Flash
        List<String> mediaNameList = null;
        boolean isMedia = false;//是否含有音视频
        List<String> fileNameList = null;
        boolean isFile = false;//是否含有文件
        boolean isMap = false;//是否含有地图


        //复制文件锁
        List<String> fileLock_list = new ArrayList<>();
        List<String> oldPathFileList = new ArrayList<>();//旧路径文件

        //删除旧媒体处理任务
        List<String> delete_mediaProcessFileNameList = new ArrayList<>();//文件名称
        //删除旧媒体切片文件夹
        List<String> delete_mediaProcessDirectoryList = new ArrayList<>();//文件夹

        String old_content = "";
        if (helpId != null && helpId > 0L) {
            help = helpService.findById(helpId);
            if (help != null) {
                if (helpTypeId != null && helpTypeId > 0L) {
                    HelpType helpType = helpTypeService.findById(helpTypeId);
                    if (helpType != null) {
                        help.setHelpTypeId(helpType.getId());
                        help.setHelpTypeName(helpType.getName());

                    } else {
                        error.put("helpTypeId", "帮助不存在");
                    }
                } else {
                    error.put("helpTypeId", "帮助Id不能为空");
                }


                old_content = help.getContent();
                if (name != null && !"".equals(name.trim())) {
                    help.setName(name);
                    if (name.length() > 100) {
                        error.put("name", "不能大于200个字符");
                    }
                } else {
                    error.put("name", "帮助名称不能为空");
                }
                if (content != null && !"".equals(content.trim())) {
                    //过滤标签
                    content = textFilterManage.filterTag(request, content);
                    Object[] object = textFilterManage.filterHtml(request, content, "help", null);
                    String value = (String) object[0];
                    imageNameList = (List<String>) object[1];
                    isImage = (Boolean) object[2];//是否含有图片
                    flashNameList = (List<String>) object[3];
                    isFlash = (Boolean) object[4];//是否含有Flash
                    mediaNameList = (List<String>) object[5];
                    isMedia = (Boolean) object[6];//是否含有音视频
                    fileNameList = (List<String>) object[7];
                    isFile = (Boolean) object[8];//是否含有文件
                    isMap = (Boolean) object[9];//是否含有地图

                    //修改文件路径
                    Object[] path_object = textFilterManage.updateTypePath(value, "help", helpTypeId);
                    String new_value = (String) path_object[0];
                    Map<String, String> file_path = (Map<String, String>) path_object[1];//key:旧文件路径  value:新文件路径

                    if (file_path != null && file_path.size() > 0) {
                        for (Map.Entry<String, String> entry : file_path.entrySet()) {//key:旧文件路径  value:新文件路径

                            //旧路径 左斜杆路径转为系统路径
                            String old_path_Delimiter = FileUtil.toSystemPath(entry.getKey());

                            //新路径 左斜杆路径转为系统路径
                            String new_path_Delimiter = FileUtil.toSystemPath(entry.getValue());

                            //替换路径中的..号
                            old_path_Delimiter = FileUtil.toRelativePath(old_path_Delimiter);
                            new_path_Delimiter = FileUtil.toRelativePath(new_path_Delimiter);

                            //复制文件到新路径
                            fileManage.copyFile(old_path_Delimiter, new_path_Delimiter);
                            //取得文件名称
                            String fileName = FileUtil.getName(entry.getKey());

                            //新建文件锁到新路径
                            //生成锁文件名称
                            String lockFileName = StringUtils.replaceOnce(entry.getValue(), "file/help/", "")
                                    + fileName;
                            lockFileName = lockFileName.replaceAll("/", "_");

                            fileLock_list.add(lockFileName);
                            //添加文件锁
                            fileManage.addLock("file" + File.separator + "help" + File.separator + "lock"
                                    + File.separator, lockFileName);
                            //旧路径文件
                            oldPathFileList.add(old_path_Delimiter);

                            //判断路径类型
                            int type = textFilterManage.isPathType(entry.getKey(), "help");
                            if (type == 30 && !StringUtils.startsWithIgnoreCase(entry.getKey(), "file/help/null/")) {//如果不是新影音

                                String newDirectory = FileUtil.getFullPath(old_path_Delimiter)
                                        + FileUtil.getBaseName(entry.getKey()) + "/";
                                fileManage.copyDirectory(newDirectory, new_path_Delimiter);

                                delete_mediaProcessFileNameList.add(FileUtil.getName(entry.getKey()));

                                delete_mediaProcessDirectoryList.add(FileUtil.toSystemPath(FileUtil.getFullPath(entry.getKey()))
                                        + FileUtil.getBaseName(entry.getKey()) + File.separator);
                            }
                        }
                    }
                    //不含标签内容
                    String text = textFilterManage.filterText(content);
                    //清除空格&nbsp;
                    String trimSpace = com.lefevre.cms.utils.StringUtil.replaceSpace(text).trim();

                    if (isImage || isFlash || isMedia || isFile || isMap || (!"".equals(text.trim()) && !"".equals(trimSpace))) {
                        String username = "";//用户名称

                        Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                        if (obj instanceof UserDetails) {
                            username = ((UserDetails) obj).getUsername();
                        }
                        help.setUserName(username);
                        help.setContent(new_value);
                    } else {
                        error.put("content", "帮助内容不能为空");
                    }
                } else {
                    error.put("content", "帮助内容不能为空");
                }
            } else {
                error.put("helpId", "帮助不存在");
            }
        } else {
            error.put("helpId", "帮助Id不能为空");
        }
        if (error.size() == 0) {
            helpService.updateHelp(help);
            //分隔符
            String separator = "";
            if ("\\".equals(File.separator)) {
                separator = "\\\\";
            } else {
                separator = "/";
            }

            Object[] obj = textFilterManage.readPathName(old_content, "help");
            if (obj != null && obj.length > 0) {
                //新增媒体处理任务
                if (isMedia) {
                    List<MediaProcessQueue> mediaProcessQueueList = new ArrayList<MediaProcessQueue>();
                    //旧影音
                    List<String> old_mediaNameList = (List<String>) obj[2];
                    A:
                    for (String fullPathName : mediaNameList) {
                        if (StringUtils.startsWithIgnoreCase(fullPathName, "null/")) {//新上传影音路径
                            //替换指定的字符，只替换第一次出现的
                            fullPathName = StringUtils.replaceOnce("/" + fullPathName, "/null/",
                                    help.getHelpTypeId() + "/");

                        }
                        for (String old_fullPathName : old_mediaNameList) {
                            if (old_fullPathName.equals("file/help/" + fullPathName)) {
                                continue A;
                            }
                        }
                        //取得路径名称
                        String pathName = FileUtil.getFullPath(fullPathName);
                        //文件名称
                        String fileName = FileUtil.getName(fullPathName);

                        MediaProcessQueue mediaProcessQueue = new MediaProcessQueue();
                        mediaProcessQueue.setModule(60);//60:在线帮助
                        mediaProcessQueue.setType(10);//10:视频
                        mediaProcessQueue.setParameter(String.valueOf(help.getId()));
                        mediaProcessQueue.setPostTime(help.getTimes());
                        mediaProcessQueue.setFilePath("file/help/" + pathName);
                        mediaProcessQueue.setFileName(fileName);
                        mediaProcessQueueList.add(mediaProcessQueue);
                    }
                    mediaProcessService.saveMediaProcessQueueList(mediaProcessQueueList);
                }

                //旧图片
                List<String> old_imageNameList = (List<String>) obj[0];
                if (old_imageNameList != null && old_imageNameList.size() > 0) {

                    Iterator<String> iter = old_imageNameList.iterator();
                    while (iter.hasNext()) {
                        String imageName = iter.next();
                        for (String new_imageName : imageNameList) {
                            if (imageName.equals("file/help/" + new_imageName)) {
                                iter.remove();
                                break;
                            }
                        }
                    }
                    if (old_imageNameList.size() > 0) {
                        for (String imageName : old_imageNameList) {
                            oldPathFileList.add(FileUtil.toSystemPath(imageName));
                        }
                    }
                }

                //旧Flash
                List<String> old_flashNameList = (List<String>) obj[1];
                if (old_flashNameList != null && old_flashNameList.size() > 0) {
                    Iterator<String> iter = old_flashNameList.iterator();
                    while (iter.hasNext()) {
                        String flashName = iter.next();
                        for (String new_flashName : flashNameList) {
                            if (flashName.equals("file/help/" + new_flashName)) {
                                iter.remove();
                                break;
                            }
                        }
                    }
                    if (old_flashNameList.size() > 0) {
                        for (String flashName : old_flashNameList) {
                            oldPathFileList.add(FileUtil.toSystemPath(flashName));
                        }
                    }
                }
                //旧影音
                List<String> old_mediaNameList = (List<String>) obj[2];
                if (old_mediaNameList != null && old_mediaNameList.size() > 0) {
                    Iterator<String> iter = old_mediaNameList.iterator();
                    while (iter.hasNext()) {
                        String mediaName = iter.next();
                        for (String new_mediaName : mediaNameList) {
                            if (mediaName.equals("file/help/" + new_mediaName)) {
                                iter.remove();
                                break;
                            }
                        }
                    }
                    if (old_mediaNameList.size() > 0) {
                        for (String mediaName : old_mediaNameList) {
                            oldPathFileList.add(FileUtil.toSystemPath(mediaName));
                            delete_mediaProcessFileNameList.add(FileUtil.getName(mediaName));

                            delete_mediaProcessDirectoryList.add(FileUtil.toSystemPath(FileUtil.getFullPath(mediaName))
                                    + FileUtil.getBaseName(mediaName) + File.separator);
                        }
                    }
                }

                //旧文件
                List<String> old_fileNameList = (List<String>) obj[3];
                if (old_fileNameList != null && old_fileNameList.size() > 0) {
                    Iterator<String> iter = old_fileNameList.iterator();
                    while (iter.hasNext()) {
                        String fileName = iter.next();
                        for (String new_fileName : fileNameList) {
                            if (fileName.equals("file/help/" + new_fileName)) {
                                iter.remove();
                                break;
                            }
                        }
                    }
                    if (old_fileNameList.size() > 0) {
                        for (String fileName : old_fileNameList) {
                            oldPathFileList.add(FileUtil.toSystemPath(fileName));
                        }
                    }
                }

                //删除旧媒体处理任务
                if (delete_mediaProcessFileNameList.size() > 0) {
                    mediaProcessService.deleteMediaProcessQueue(delete_mediaProcessFileNameList);
                    //删除缓存
                    for (String delete_mediaProcessFileName : delete_mediaProcessFileNameList) {
                        mediaProcessQueueManage.delete_cache_findMediaProcessQueueByFileName(delete_mediaProcessFileName);
                    }
                }
                //删除旧媒体切片文件夹
                if (delete_mediaProcessDirectoryList.size() > 0) {
                    for (String mediaProcessDirectory : delete_mediaProcessDirectoryList) {
                        if (mediaProcessDirectory != null && !"".equals(mediaProcessDirectory.trim())) {
                            fileManage.removeDirectory(mediaProcessDirectory);
                        }
                    }
                }
            }
            //删除图片锁
            if (imageNameList != null && imageNameList.size() > 0) {
                for (String imageName : imageNameList) {
                    if (imageName != null && !"".equals(imageName.trim())) {
                        fileManage.deleteLock("file" + File.separator + "help" + File.separator + "lock"
                                + File.separator, imageName.replaceAll("/", "_"));
                    }
                }
            }
            //删除Falsh锁
            if (flashNameList != null && flashNameList.size() > 0) {
                for (String flashName : flashNameList) {
                    if (flashName != null && !"".equals(flashName.trim())) {
                        fileManage.deleteLock("file" + File.separator + "help" + File.separator + "lock"
                                + File.separator, flashName.replaceAll("/", "_"));
                    }
                }
            }
            //删除音视频锁
            if (mediaNameList != null && mediaNameList.size() > 0) {
                for (String mediaName : mediaNameList) {
                    if (mediaName != null && !"".equals(mediaName.trim())) {
                        fileManage.deleteLock("file" + File.separator + "help" + File.separator + "lock"
                                + File.separator, mediaName.replaceAll("/", "_"));
                    }
                }
            }
            //删除文件锁
            if (fileNameList != null && fileNameList.size() > 0) {
                for (String fileName : fileNameList) {
                    if (fileName != null && !"".equals(fileName.trim())) {
                        fileManage.deleteLock("file" + File.separator + "help" + File.separator + "lock"
                                + File.separator, fileName.replaceAll("/", "_"));

                    }
                }
            }
            //删除复制文件锁
            if (fileLock_list.size() > 0) {
                for (String fileName : fileLock_list) {
                    if (fileName != null && !"".equals(fileName.trim())) {
                        fileManage.deleteLock("file" + File.separator + "help" + File.separator + "lock"
                                + File.separator, fileName.replaceAll("/", "_"));
                    }
                }
            }

            //删除旧路径文件
            if (oldPathFileList.size() > 0) {
                for (String oldPathFile : oldPathFileList) {
                    //替换路径中的..号
                    oldPathFile = FileUtil.toRelativePath(oldPathFile);

                    //删除旧路径文件
                    Boolean state = fileManage.deleteFile(oldPathFile);
                    if (state != null && !state) {
                        //替换指定的字符，只替换第一次出现的
                        oldPathFile = StringUtils.replaceOnce(oldPathFile, "file" + File.separator + "help"
                                + File.separator, "");

                        //创建删除失败文件
                        fileManage.failedStateFile("file" + File.separator + "help" + File.separator + "lock"
                                + File.separator + FileUtil.toUnderline(oldPathFile));
                    }
                }
            }
            return JsonUtils.toJSONString(new RequestResult(ResultCode.SUCCESS, null));
        }
        return JsonUtils.toJSONString(new RequestResult(ResultCode.FAILURE, error));
    }

    /**
     * 帮助   删除
     *
     * @param helpId
     */
    @ResponseBody
    @RequestMapping(params = "method=delete", method = RequestMethod.POST)
    public String delete(Long[] helpId) throws Exception {

        Map<String, String> error = new HashMap<>();

        if (helpId != null && helpId.length > 0) {
            List<Long> helpIdList = new ArrayList<>();
            for (Long l : helpId) {
                if (l != null && l > 0L) {
                    helpIdList.add(l);
                }
            }
            if (helpIdList.size() > 0) {
                List<Help> helpList = helpService.findByIdList(helpIdList);
                if (helpList != null && helpList.size() > 0) {
                    for (Help help : helpList) {
                        if (help.isVisible()) {//标记删除
                            int i = helpService.markDelete(help.getHelpTypeId(), help.getId());
                        } else {//物理删除
                            int i = helpService.deleteHelp(help.getHelpTypeId(), help.getId(), 0L);

                            Object[] obj = textFilterManage.readPathName(help.getContent(), "help");
                            if (obj != null && obj.length > 0) {
                                List<String> filePathList = new ArrayList<>();

                                //删除旧媒体处理任务
                                List<String> delete_mediaProcessFileNameList = new ArrayList<>();//文件名称
                                //删除旧媒体切片文件夹
                                List<String> delete_mediaProcessDirectoryList = new ArrayList<>();//文件夹

                                //删除图片
                                List<String> imageNameList = (List<String>) obj[0];
                                filePathList.addAll(imageNameList);
                                //删除Flash
                                List<String> flashNameList = (List<String>) obj[1];
                                filePathList.addAll(flashNameList);
                                //删除影音
                                List<String> mediaNameList = (List<String>) obj[2];
                                for (String mediaName : mediaNameList) {
                                    filePathList.add(mediaName);
                                    delete_mediaProcessFileNameList.add(FileUtil.getName(mediaName));

                                    delete_mediaProcessDirectoryList.add(FileUtil.toSystemPath(FileUtil.getFullPath(mediaName))
                                            + FileUtil.getBaseName(mediaName) + File.separator);

                                }
                                //删除文件
                                List<String> fileNameList = (List<String>) obj[3];
                                filePathList.addAll(fileNameList);

                                for (String filePath : filePathList) {
                                    //替换路径中的..号
                                    filePath = FileUtil.toRelativePath(filePath);
                                    filePath = FileUtil.toSystemPath(filePath);
                                    //删除旧路径文件
                                    Boolean state = fileManage.deleteFile(filePath);
                                    if (state != null && !state) {
                                        //替换指定的字符，只替换第一次出现的
                                        filePath = StringUtils.replaceOnce(filePath, "file" + File.separator + "help"
                                                + File.separator, "");

                                        //创建删除失败文件
                                        fileManage.failedStateFile("file" + File.separator + "help" + File.separator + "lock"
                                                + File.separator + FileUtil.toUnderline(filePath));
                                    }
                                }

                                //删除旧媒体处理任务
                                if (delete_mediaProcessFileNameList.size() > 0) {
                                    mediaProcessService.deleteMediaProcessQueue(delete_mediaProcessFileNameList);

                                    //删除缓存
                                    for (String delete_mediaProcessFileName : delete_mediaProcessFileNameList) {
                                        mediaProcessQueueManage.delete_cache_findMediaProcessQueueByFileName(delete_mediaProcessFileName);
                                    }
                                }
                                //删除旧媒体切片文件夹
                                if (delete_mediaProcessDirectoryList.size() > 0) {
                                    for (String mediaProcessDirectory : delete_mediaProcessDirectoryList) {
                                        if (mediaProcessDirectory != null && !"".equals(mediaProcessDirectory.trim())) {
                                            fileManage.removeDirectory(mediaProcessDirectory);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    return JsonUtils.toJSONString(new RequestResult(ResultCode.SUCCESS, null));
                } else {
                    error.put("helpId", "帮助不存在");
                }
            }
        } else {
            error.put("helpId", "帮助Id不能为空");
        }
        return JsonUtils.toJSONString(new RequestResult(ResultCode.FAILURE, error));
    }

    /**
     * 还原
     *
     * @param helpId 帮助Id集合
     */
    @ResponseBody
    @RequestMapping(params = "method=reduction", method = RequestMethod.POST)
    public String reduction(Long[] helpId) throws Exception {
        Map<String, String> error = new HashMap<>();
        if (helpId != null && helpId.length > 0) {
            List<Help> helpList = helpService.findByIdList(Arrays.asList(helpId));
            if (helpList != null && helpList.size() > 0) {
                helpService.reductionHelp(helpList);
                return JsonUtils.toJSONString(new RequestResult(ResultCode.SUCCESS, null));
            } else {
                error.put("helpId", "帮助不存在");
            }
        } else {
            error.put("helpId", "帮助Id不能为空");
        }
        return JsonUtils.toJSONString(new RequestResult(ResultCode.FAILURE, error));
    }

    /**
     * 移动
     *
     * @param helpId 帮助Id集合
     */
    @ResponseBody
    @RequestMapping(params = "method=move", method = RequestMethod.POST)
    public String move(Long[] helpId, Long helpTypeId) throws Exception {
        Map<String, String> error = new HashMap<>();

        if (helpId != null && helpId.length > 0) {

            List<Help> helpList = helpService.findByIdList(Arrays.asList(helpId));

            //复制文件锁
            List<String> fileLock_list = new ArrayList<>();
            List<String> pathFileList = new ArrayList<>();//旧路径文件

            //删除旧媒体处理任务
            List<String> delete_mediaProcessFileNameList = new ArrayList<>();//文件名称
            //删除旧媒体切片文件夹
            List<String> delete_mediaProcessDirectoryList = new ArrayList<>();//文件夹

            if (helpList != null && helpList.size() > 0) {
                for (Help help : helpList) {
                    //修改文件路径
                    Object[] path_object = textFilterManage.updateTypePath(help.getContent(), "help", helpTypeId);
                    String new_value = (String) path_object[0];

                    help.setContent(new_value);
                    Map<String, String> file_path = (Map<String, String>) path_object[1];//key:旧文件路径  value:新文件路径

                    if (file_path != null && file_path.size() > 0) {
                        for (Map.Entry<String, String> entry : file_path.entrySet()) {//key:旧文件路径  value:新文件路径

                            //旧路径 左斜杆路径转为系统路径
                            String old_path_Delimiter = FileUtil.toSystemPath(entry.getKey());

                            //新路径 左斜杆路径转为系统路径
                            String new_path_Delimiter = FileUtil.toSystemPath(entry.getValue());

                            //替换路径中的..号
                            old_path_Delimiter = FileUtil.toRelativePath(old_path_Delimiter);
                            new_path_Delimiter = FileUtil.toRelativePath(new_path_Delimiter);

                            //复制文件到新路径
                            fileManage.copyFile(old_path_Delimiter, new_path_Delimiter);
                            //取得文件名称
                            String fileName = FileUtil.getName(entry.getKey());

                            //新建文件锁到新路径
                            //生成锁文件名称
                            String lockFileName = StringUtils.replaceOnce(entry.getValue(), "file/help/", "")
                                    + fileName;
                            lockFileName = lockFileName.replaceAll("/", "_");

                            fileLock_list.add(lockFileName);
                            //添加文件锁
                            fileManage.addLock("file" + File.separator + "help" + File.separator + "lock"
                                    + File.separator, lockFileName);
                            //旧路径文件
                            pathFileList.add(old_path_Delimiter);

                            //判断路径类型
                            int type = textFilterManage.isPathType(entry.getKey(), "help");
                            if (type == 30) {//影音
                                String newDirectory = FileUtil.getFullPath(old_path_Delimiter)
                                        + FileUtil.getBaseName(entry.getKey()) + "/";
                                fileManage.copyDirectory(newDirectory, new_path_Delimiter);

                                delete_mediaProcessFileNameList.add(FileUtil.getName(entry.getKey()));
                                delete_mediaProcessDirectoryList.add(FileUtil.toSystemPath(FileUtil.getFullPath(entry.getKey()))
                                        + FileUtil.getBaseName(entry.getKey()) + File.separator);
                            }
                        }
                    }
                }
            } else {
                error.put("helpId", "帮助不存在");
            }
            if (error.size() == 0) {
                helpService.updateHelp(helpList, helpTypeId);
                //删除复制文件锁
                if (fileLock_list.size() > 0) {
                    for (String fileName : fileLock_list) {
                        if (fileName != null && !"".equals(fileName.trim())) {
                            fileManage.deleteLock("file" + File.separator + "help" + File.separator + "lock"
                                    + File.separator, fileName.replaceAll("/", "_"));
                        }
                    }
                }
                //删除旧路径文件
                if (pathFileList.size() > 0) {
                    for (String pathFile : pathFileList) {
                        //替换路径中的..号
                        pathFile = FileUtil.toRelativePath(pathFile);

                        //删除旧路径文件
                        Boolean state = fileManage.deleteFile(pathFile);
                        if (state != null && !state) {
                            //替换指定的字符，只替换第一次出现的
                            pathFile = StringUtils.replaceOnce(pathFile, "file" + File.separator + "help"
                                    + File.separator, "");

                            //创建删除失败文件
                            fileManage.failedStateFile("file" + File.separator + "help" + File.separator + "lock"
                                    + File.separator + FileUtil.toUnderline(pathFile));
                        }
                    }
                }

                //删除旧媒体处理任务
                if (delete_mediaProcessFileNameList.size() > 0) {
                    mediaProcessService.deleteMediaProcessQueue(delete_mediaProcessFileNameList);
                    //删除缓存
                    for (String delete_mediaProcessFileName : delete_mediaProcessFileNameList) {
                        mediaProcessQueueManage.delete_cache_findMediaProcessQueueByFileName(delete_mediaProcessFileName);
                    }
                }
                //删除旧媒体切片文件夹
                if (delete_mediaProcessDirectoryList.size() > 0) {
                    for (String mediaProcessDirectory : delete_mediaProcessDirectoryList) {
                        if (mediaProcessDirectory != null && !"".equals(mediaProcessDirectory.trim())) {
                            fileManage.removeDirectory(mediaProcessDirectory);
                        }
                    }
                }
            }
            return JsonUtils.toJSONString(new RequestResult(ResultCode.SUCCESS, null));
        } else {
            error.put("helpId", "帮助Id不能为空");
        }
        return JsonUtils.toJSONString(new RequestResult(ResultCode.FAILURE, error));
    }

    /**
     * 搜索帮助分页
     *
     * @param keyword 关键词
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "method=ajax_searchHelpPage", method = RequestMethod.GET)
    public String searchHelpPage(PageForm pageForm, String keyword) {
        //调用分页算法代码
        PageView<Help> pageView = new PageView<>(settingService.findSystemSetting_cache().getBackstagePageNumber(), pageForm.getPage(), 10);
        int firstindex = (pageForm.getPage() - 1) * pageView.getMaxresult();

        LambdaQueryWrapper<Help> wrapper = new LambdaQueryWrapper<>();

        if (keyword != null && !"".equals(keyword.trim())) {
            String searchName_utf8 = "";
            try {
                searchName_utf8 = URLDecoder.decode(keyword.trim(), "utf-8");
            } catch (UnsupportedEncodingException e) {
                logger.error("搜索帮助名称编码错误", e);
            }
            wrapper.like(Help::getName, searchName_utf8.trim());
            // jpql.append(" and o.name like ?").append((params.size() + 1)).append(" escape '/' ");
        }
        wrapper.eq(Help::isVisible, true);
        QueryResult<Help> qr = new QueryResult<>();

        Page<Help> helpPage = helpService.page(new Page<>(firstindex, pageView.getMaxresult()), wrapper);
        qr.setResultlist(helpPage.getRecords());
        qr.setTotalrecord(helpPage.getTotal());

        pageView.setQueryResult(qr);

        return JsonUtils.toJSONString(new RequestResult(ResultCode.SUCCESS, pageView));
    }
}
